/*
 * @Author: xiehangyun 
 * @Date: 2025-05-16 10:49:46 
 * @Last Modified by: 肖思汗
 * @Last Modified time: 2025-08-05 14:17:24
 */

import { autorun, makeAutoObservable } from "mobx";
import userStore from "src/pages/User/userStore";
import { CouponItem, DistributionModeData } from "types/type";
import addressManageStore from "../AddressManage/addressManageStore";
import confirmOrderApi from "./ConfirmOrderApi";

class ConfirmOrderStore {
    constructor() {
        makeAutoObservable(this, {}, { deep: false });
    }

    coupon?: CouponItem;
    // 设置优惠券id
    setCoupon(coupon?: CouponItem) {
        this.coupon = coupon;
    }

    // 配送方式列表
    distributionMode: Array<DistributionModeData> = [];
    activeDistributionMode = 0;
    setDistributionMode(id: number) {
        this.activeDistributionMode = id;
    }
    // 获取配送方式列表
    async getDistributionMode() {
        const res = await confirmOrderApi.listDistributionMode();
        if (res.code === 200) {
            this.distributionMode = res.rows;
            // 默认选择申通快递，如果没有则选择第一个配送方式
            const fristActive = res.rows.find(item => item.companyName.includes('申通')) || res.rows[0];
            if (fristActive) {
                this.activeDistributionMode = fristActive.distributionModeId;
            }
        }
    }

    commonPackage = 0; //普通包装
    advencedPackage = 12; // 高级包装

    async getPackges(appAddressId, distributionModeId) {
        const res = await confirmOrderApi.getPackges(appAddressId, distributionModeId);
        if (res.code === 200) {
            this.commonPackage = res.data.commonPackage;
            this.advencedPackage = res.data.advencedPackage;
        }
    }
    // 获取包装费用map
    packgeType = 0; // 包装方式 0 普通 1 高级
    setPackgeType(packgeType: number) {
        this.packgeType = packgeType;
    }

}

const confirmOrderStore = new ConfirmOrderStore();

export default confirmOrderStore;

autorun(() => {
    if (userStore.isLogin) {
        confirmOrderStore.getDistributionMode();
    }
});

//  获取包装费用map
autorun(() => {
    const { activeDistributionMode } = confirmOrderStore;
    const { selectedAddressId } = addressManageStore;
    if (userStore.isLogin && selectedAddressId > 0 && activeDistributionMode > 0) {
        confirmOrderStore.getPackges(selectedAddressId, activeDistributionMode);
    }
}, { delay: 30 });







